package com.wdhcr.osspolicy.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.wdhcr.osspolicy.annotation.OssConverterUrl;
import com.wdhcr.osspolicy.enums.UrlConverterType;

import java.io.IOException;
import java.util.Objects;

public class UrlConverterJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private UrlConverterType urlConverterType;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (Objects.nonNull(urlConverterType)) {
            jsonGenerator.writeString(urlConverterType.getDeserialize().apply(s));
        }else {
            jsonGenerator.writeString(s);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        OssConverterUrl converterUrl = beanProperty.getAnnotation(OssConverterUrl.class);
        if (Objects.nonNull(converterUrl) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
            this.urlConverterType = converterUrl.type();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}
